package com.dragon.graduation.proposalReport.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dragon.config.exception.exception.GlobalException;
import com.dragon.graduation.project.entity.ProjectEntity;
import com.dragon.graduation.project.service.ProjectService;
import com.dragon.graduation.projectApplication.controller.dto.ApplicationAuditDTO;
import com.dragon.graduation.projectApplication.entity.ProjectApplicationEntity;
import com.dragon.graduation.projectApplication.service.ProjectApplicationService;
import com.dragon.graduation.projectProgress.service.ProjectProgressService;
import com.dragon.graduation.proposalReport.controller.dto.ProposalReportAddDTO;
import com.dragon.graduation.proposalReport.controller.dto.ProposalReportSearchDTO;
import com.dragon.graduation.proposalReport.controller.dto.ProposalReportUpdateDTO;
import com.dragon.graduation.proposalReport.controller.vo.ProposalReportVO;
import com.dragon.graduation.proposalReport.entity.ProposalReportEntity;
import com.dragon.graduation.proposalReport.service.ProposalReportService;
import com.dragon.graduation.student.service.StudentService;
import com.dragon.graduation.teacher.service.TeacherService;
import com.dragon.graduation.user.controller.vo.UserVO;
import com.dragon.jwt.JwtUtil;
import com.dragon.results.page.ResultPage;
import com.dragon.results.result.HttpResult;
import com.dragon.util.MyPage;
import com.dragon.utils.LocalFileUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 开题报告表 前端控制器
 * </p>
 *
 * @author dragon
 * @since 2025-02-28 21:20:54
 */
@RestController
@RequestMapping("/proposalReport")
@RequiredArgsConstructor
@Api(tags = "开题报告表 相关接口")
public class ProposalReportController {

    private final ProposalReportService proposalReportService;
    private final StudentService studentService;
    private final TeacherService teacherService;
    private final ProjectService projectService;
    private final LocalFileUtil localFileUtil;
    private final ProjectApplicationService projectApplicationService;
    private final ProjectProgressService projectProgressService;


    @PostMapping("add")
    @ApiOperation("1]开题报告表添加")
    @ApiOperationSupport(order = 1)
    public HttpResult<String> add(@RequestBody ProposalReportAddDTO addDTO) {
        UserVO userVO = JwtUtil.parseToken(JwtUtil.getTokenFromRequest(), UserVO.class);
        ProjectApplicationEntity projectApplication = projectApplicationService.lambdaQuery()
                .eq(ProjectApplicationEntity::getStudentId, userVO.getRoleId())
                .eq(ProjectApplicationEntity::getProjectId, addDTO.getProjectId())
                .orderByDesc(ProjectApplicationEntity::getUpdateTime)
                .last("limit 1").one();
        if (projectApplication.getStatus()!=1) {
            localFileUtil.deleteFile(addDTO.getDocumentPath());
            throw new GlobalException("您当前题目的申请未通过，不可提交开题报告");
        }

        ProposalReportEntity proposalReportEntity = proposalReportService.findByProjectIdAndStudentId(userVO.getRoleId(), addDTO.getProjectId());
        if (ObjectUtils.isNotEmpty(proposalReportEntity)) {
            String message;
            if (proposalReportEntity.getStatus() == 0) {
                message = "您当前题目的开题报告未审核，不可重复提交";
            } else {
                message = "您当前题目的开题报告已审核通过，不可重复提交";
            }
            localFileUtil.deleteFile(addDTO.getDocumentPath());
            throw new GlobalException(message);
        }
        ProposalReportEntity entity = ProposalReportAddDTO.to(addDTO, ProposalReportEntity.class);
        entity.setStatus(0);
        entity.setStudentId(userVO.getRoleId());
        entity.setSubmissionTime(LocalDateTime.now());
        proposalReportService.save(entity);
        projectProgressService.record(userVO.getRoleId(),addDTO.getProjectId(),2,0);
        return HttpResult.ok("添加成功");
    }

    @PostMapping("update")
    @ApiOperation("2]开题报告表修改")
    @ApiOperationSupport(order = 2)
    public HttpResult<String> update(@RequestBody ProposalReportUpdateDTO updateDTO) {
        ProposalReportEntity entity = proposalReportService.getById(updateDTO.getId());
        Assert.isFalse(ObjectUtils.isEmpty(entity), () -> new GlobalException("要修改的数据不存在"));
        entity = ProposalReportUpdateDTO.to(updateDTO, ProposalReportEntity.class);
        proposalReportService.updateById(entity);
        return HttpResult.ok("修改成功");
    }

    @PostMapping("search")
    @ApiOperation("3]开题报告表分页查询")
    @ApiOperationSupport(order = 3)
    public HttpResult<ResultPage<List<ProposalReportVO>>> search(@RequestBody ProposalReportSearchDTO searchDTO) {
        UserVO userVO = JwtUtil.parseToken(JwtUtil.getTokenFromRequest(), UserVO.class);
        if (userVO.getRole() != 1) {
            if (userVO.getRole() == 2) {
                //学生看自己的开题报告
                searchDTO.setStudentId(userVO.getRoleId());
            } else {
                //老师看自己项目下的所有
                List<ProjectEntity> projectEntities = projectService.findByTeacherId(userVO.getRoleId());
                if (!CollectionUtils.isEmpty(projectEntities)) {
                    List<Integer> collected = projectEntities.stream().map(ProjectEntity::getId).collect(Collectors.toList());
                    searchDTO.setProjectList(collected);
                }
            }
        }
        Page<ProposalReportEntity> entityPage = MyPage.setPage(ProposalReportEntity.class, searchDTO.getPage());
        Page<ProposalReportVO> page = proposalReportService.pages(entityPage, searchDTO);
        ResultPage<List<ProposalReportVO>> resultPage = MyPage.copyPage(page, ProposalReportVO.class);
        return HttpResult.okForData(resultPage);
    }

    @PostMapping("delete")
    @ApiOperation("4]开题报告表删除")
    @ApiOperationSupport(order = 4)
    public HttpResult<String> delete(@RequestBody List<Integer> idList) {
        proposalReportService.removeByIds(idList);
        return HttpResult.ok("删除成功");
    }

    @PostMapping("audit")
    @ApiOperation("5]审核开题报告")
    @ApiOperationSupport(order = 5)
    public HttpResult<String> audit(@RequestBody ApplicationAuditDTO auditDTO){
        ProposalReportEntity entity = proposalReportService.getById(auditDTO.getId());
        Assert.isFalse(ObjectUtils.isEmpty(entity), () -> new GlobalException("要审核的数据不存在"));
        Assert.isFalse(entity.getStatus() != 0, () -> new GlobalException("该申请已审核;不可重复审核"));
        entity.setStatus(auditDTO.getStatus());
        entity.setReviewComment(auditDTO.getReviewComment());
        UserVO userVO = JwtUtil.parseToken(JwtUtil.getTokenFromRequest(), UserVO.class);
        entity.setReviewerId(userVO.getId());
        entity.setReviewTime(LocalDateTime.now());
        proposalReportService.updateById(entity);
        if (entity.getStatus()==1) {
            projectProgressService.record(entity.getStudentId(),entity.getProjectId(),2,1);
        }else {
            projectProgressService.record(entity.getStudentId(),entity.getProjectId(),2,2);
        }
        return HttpResult.ok("操作成功");
    }

}
